package com.hhp.cloud.shop.auth.common.exception;

import com.hhp.cloud.shop.common.core.enums.BizCodeEnume;
import com.hhp.cloud.shop.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description: 认证异常处理器
 * @author: hhp
 * @date: 2021/11/23 17:06
 */
@RestControllerAdvice
@Slf4j
public class AuthExceptionHandler {

    /**
     * @Description: 用户不存在
     * @author: hhp
     * @Param: * @param e
     * @return: * @return
     * @date 2021/11/24 10:29
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(UsernameNotFoundException.class)
    public R handleUsernameNotFoundException(UsernameNotFoundException e) {
        return R.error(BizCodeEnume.USER_NOT_EXIST);
    }

    /**
     * @Description: 用户名或密码错误
     * @author: hhp
     * @Param: * @param e
     * @return: * @return
     * @date 2021/11/24 10:30
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidGrantException.class)
    public R handleInvalidGrantException(InvalidGrantException e) {
        return R.error(BizCodeEnume.USERNAME_OR_PASSWORD_ERROR);
    }


    /**
     * @Description: 账户异常
     * @author: hhp
     * @Param: * @param e
     * @return: * @return
     * @date 2021/11/24 10:30
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public R handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return R.error(e.getMessage());
    }

    /**
     * @Description: token过期或无效
     * @author: hhp
     * @Param: * @param e
     * @return: * @return
     * @date 2021/11/24 10:31
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({InvalidTokenException.class})
    public R handleInvalidTokenExceptionException(InvalidTokenException e) {
        return R.error(e.getMessage());
    }

}
